package com.zyd.shiro.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyd.shiro.business.entity.User;
import com.zyd.shiro.business.service.ChannelService;
import com.zyd.shiro.business.service.MallRegionService;
import com.zyd.shiro.business.service.SysUserService;
import com.zyd.shiro.business.vo.UserConditionVO;
import com.zyd.shiro.persistence.beans.Channel;
import com.zyd.shiro.persistence.dao.SysChannelDao;
import com.zyd.shiro.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChannelServiceImpl implements ChannelService {

    @Autowired
    private SysChannelDao channelDao;

    @Autowired
    private SnowflakeIdWorker worker;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private MallRegionService regionService;

    @Override
    public Channel findOne(int id) {
        return channelDao.findOne(id);
    }

    public List<Channel> volist(UserConditionVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<User> users = sysUserService.listByRoleId(3L);
        List<Channel> channels = new ArrayList<>();
        if (users != null)
            for (User user : users) {
                Channel channel = null;
                if (!StringUtils.isEmpty(user.getRemark())) {
                    channel = channelDao.findOne(Integer.valueOf(user.getRemark()));
                    if (channel != null) {
                        channel.setRegions(regionService.findOne(channel.getRegion()));
                    }
                }
                if (channel == null)
                    channel = new Channel();
                channel.setUser(user);
                channels.add(channel);
            }
        return channels;
    }

    public Channel getChannelByUserId(Integer uid)
    {
        return channelDao.getChannelByUserId(uid);
    }


    @Override
    public Integer save(Channel channel) {
        if (channel.getId() != null && channel.getId() != 0) {
            return channelDao.saveAndFlush(channel).getId();
        } else {
            channel.setId(0);
            channel.setUID(String.valueOf(worker.nextId()));
            return channelDao.saveAndFlush(channel).getId();
        }
    }
}
